package com.example.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
public class LoggingFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();

        // 获取客户端IP地址
        String ip = request.getRemoteAddress() != null ? request.getRemoteAddress().getAddress().getHostAddress() : "Unknown";

        // 记录IP和请求行
        log.info("Request from IP: {}, Method: {}, Path: {}", ip, request.getMethod(), request.getPath());

        String realIp = request.getHeaders().getFirst("X-Forwarded-For");
        log.info("X-Forwarded-For: {}", realIp);

        // 继续 filter 链的处理，如果没有这步操作会导致 Gateway 转发失效
        return chain.filter(exchange);
    }
}
